<template>
<!-- immediate-check是否在初始化时立即执行滚动位置检查 -->
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :immediate-check="false"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
  >
    <!-- <van-cell v-for="(item, index) in list" :key="index" :title="item.content" /> -->
    <!-- 用户评论 -->
    <comment-item v-for="(item, index) in list" :key="index" :comment="item" @show-comment="$emit('show-comment', $event)" />
  </van-list>
</template>

<script>
import { getAllComment } from '@/api/comment'
import commentItem from './comment-item'
export default {
  name: 'commentList',
  components: {
    commentItem
  },
  props: {
    artId: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      // 自定义 prop 数据验证
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data() {
    return {
      loading: false,
      finished: false,
      offset: null,
      total: 10,
      error: false
    }
  },
  computed: {},
  watch: {},
  created() {
    // 当你手动初始 onLoad 的话，它不会自动开始初始的 loading
    // 所以我们要手动的开启初始 loading
    this.loading = true
    this.onLoad()
  },
  mounted() {},
  methods: {
    async onLoad() {
      try {
        const { data } = await getAllComment({
          type: this.type, // a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.artId.toString(), // 文章id或评论id
          offset: this.offset, // 获取新评论
          limit: this.total // 获取的评论数据个数
        })
        this.list.push(...data.data.results)
        this.$emit('total_count', data.data)
        this.loading = false
        if (data.data.results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    }
  }
}
</script>

<style scoped lang="less">
</style>
